<template>
	<a-card>
		<c-form
			:model="filter"
			:fields="filterFields"
			:label-col="{ flex: '60px' }"
			:search="{ loading, query, reset }"
		>
		</c-form>
	</a-card>

	<a-card>
		<a-table
			:rowKey="rowKey"
			:dataSource="list"
			:columns="columns"
			:loading="loading"
			:sticky="{ offsetHeader: -20 }"
			:pagination="pagination"
			:row-selection="{
				selectedRowKeys: selected.keys,
				onChange: onSelectChange
			}"
			@change="onTableChange"
		>
		</a-table>
	</a-card>

	{{ height }}
	<div>{{ isLoading }}</div>
	<div
		ref="wrap"
		class="h-200 b-solid b-emerald b-1 overflow-auto"
	>
		<div
			class="h-40"
			v-loading="true"
		></div>
		<div
			v-for="item in data"
			class="h-40 f-c-c"
			:key="item"
		>
			{{ item }}
		</div>
	</div>
</template>

<script setup lang="ts">
import { useBroadcast } from '@/hooks'
import { useInfiniteScroll, useScroll, useWindowSize } from '@vueuse/core'
import { useTemplateRef } from 'vue'
import { useFilter, useList } from './config'

const { height } = useWindowSize()
const wrapRef = useTemplateRef<HTMLElement>('wrap')
const data = ref([1, 2, 3, 4, 5, 6])
const { y } = useScroll(wrapRef)
let prevScrollHeight = 0
const { isLoading } = useInfiniteScroll(
	wrapRef,
	() => {
		// console.log("🚀 ~ isLoading:", isLoading.value)
		setTimeout(() => {
			data.value.unshift(
				...[Math.random(), Math.random() * 10, Math.random() * 10, Math.random() * 10, Math.random() * 10]
			)
			nextTick(() => {
				const scrollHeight = wrapRef.value?.scrollHeight as number
				y.value = scrollHeight - prevScrollHeight
				prevScrollHeight = scrollHeight
			})
		}, 1500)
	},
	{ distance: 30, interval: 2500, direction: 'top' }
)

const { filterFields, filter } = useFilter()
const { rowKey, list, loading, pagination, onTableChange, onSelectChange, selected, reset, query, columns } = useList({
	filter
})

const { broadcastListen } = useBroadcast('demo')
broadcastListen(reset)
</script>
